package cn.xeblog.forward.utils;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.*;

/**
 * @author eleven
 * @date 2024/12/16 8:20
 * @apiNote
 */
@Slf4j
public class YamlUtil {
    public static Map<String, Object> getProperties() {
        try(InputStream is = YamlUtil.class.getClassLoader().getResourceAsStream("application.yml")) {
            Yaml yaml = new Yaml();
            Map<String, Object> data  = yaml.load(is);
            return data;
        } catch (Exception e) {
            log.error("加载配置文件失败", e);
            return new HashMap<>();
        }
    }

    public static Object getValue(String key) {
        Map<String, Object> properties = getProperties();
        List<String> keyList = new ArrayList<>(Arrays.asList(key.split("\\.")));
        int size = keyList.size();
        for (int i = 0; i < size; i++) {
            if (i != size - 1) {
                try {
                    properties = (Map<String, Object>) properties.get(keyList.get(i));
                } catch (Exception e) {
                    log.error("获取配置 {} 失败", key, e);
                    return null;
                }
            } else {
                return properties.get(keyList.get(i));
            }
        }
        return null;
    }
}
